﻿using Home.Domain.Entities;
using Home.WebUI.Areas.Admin.Validation;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities.ViewModel;
using Omu.ValueInjecter;
using System.Data;
using Utilities.Validation;

namespace Home.WebUI.Areas.Admin.Controllers
{
    public class UserInfoController : Controller
    {
        private EFDbContext db = new EFDbContext();
        private DbSet<UserInfo> Entities
        { get { return db.UserInfos; } set { value = Entities; } }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        //
        // GET: /Admin/UserInfo/

        public ActionResult Index(PagedList<UserInfo> model, int page = 1)
        {
            //页面项数
            int pageSize = 10;
            var list = Entities.OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                list = list.Where(c => c.UserName.Contains(model.Search));
            }
            model.Entities = list;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = Entities.Count() };
            return View(model);
        }

        public ActionResult Create()
        {
            UserInfoCreate model = new UserInfoCreate();
            model.State = 1;
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(UserInfoCreate model)
        {
            //try
            //{
            if (ModelState.IsValid)
            {
                UserInfo content = new UserInfo();
                content.InjectFrom(model);
                Entities.Add(content);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //}
            //catch (DataException)
            //{
            //    TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            //}
            return View(model);
        }
        public ActionResult Edit(int id)
        {
            UserInfoEdit model = new UserInfoEdit();
            UserInfo content = Entities.Find(id);
            ViewBag.UserName = content.UserName;
            return View(model.InjectFrom(content));
        }
        [HttpPost]
        public ActionResult Edit(UserInfoEdit model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UserInfo content = Entities.Find(model.Id);
                    content.InjectFrom(model);
                    if (string.IsNullOrWhiteSpace(model.PassWord))
                    {
                        content.PassWord = db.Entry(content).OriginalValues["PassWord"].ToString();
                    }
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Edit", new { id = model.Id });
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            ViewBag.UserName = Entities.Where(e => e.Id == model.Id).Select(e => e.UserName).FirstOrDefault();
            return View(model);
        }
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    UserInfo content = new UserInfo();
                    content.Id = id;
                    db.UserInfos.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }

        //验证是否存在此标题
        [HttpGet]
        public ActionResult UserNameExists(string title, int id = 0)//id为排除的值，0无排除
        {
            //需优化
            Func<UserInfo, bool> where;
            if (id == 0)
            {
                where = c => c.UserName == title;
            }
            else
            {
                where = c => c.UserName == title && c.Id != id;
            }
            bool exists = true;
            int number = db.UserInfos.Where(where).Count();//此处传递委托不好生成的sql语句先执行后过滤的。
            if (number == 0)
            {
                exists = false;
            }
            return Json(!exists, JsonRequestBehavior.AllowGet);
        }

    }
}
